package com.htdst.mockserver.tcpserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import junit.framework.TestCase;

import org.junit.Test;

import com.htdst.mockserver.util.Constants;

public class MockSocketClient extends TestCase
{

	public static void main(String[] args) throws IOException
	{
		new SocketServer().start();
	}

	@Override
	protected void setUp() throws Exception
	{
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception
	{
		super.tearDown();
	}

	@Test
	public void testHandler()
	{
		Socket socket = null;
		DataOutputStream dos = null;
		DataInputStream dis = null;
		try
		{
			socket = new Socket("localhost", Constants.PORT);

			dos = new DataOutputStream(new BufferedOutputStream(
					socket.getOutputStream()));

			String tmp = "Test";
			dos.writeInt(tmp.length());
			dos.write(tmp.getBytes(Constants.DEFAULT_CHARSET));
			dos.flush();

			String response = null;
			dis = new DataInputStream(new BufferedInputStream(
					socket.getInputStream()));
			final int length = dis.readInt();
			byte[] bufResponse = new byte[length];
			dis.readFully(bufResponse);
			response = new String(bufResponse, Constants.DEFAULT_CHARSET);

			System.out.println(response);
			assertEquals("success", response);
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (dis != null)
			{
				try
				{
					dis.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			if (dos != null)
			{
				try
				{
					dos.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			if (socket != null)
			{
				try
				{
					socket.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}

	}

}
